package net.woggle.shackbrowseapi;

import java.io.IOException;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.*;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.CookieStore;
import org.apache.http.client.HttpResponseException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.params.ClientPNames;
import org.apache.http.client.params.CookiePolicy;
import org.apache.http.client.params.HttpClientParams;
import org.apache.http.client.protocol.ClientContext;
import org.apache.http.cookie.CookieSpec;
import org.apache.http.cookie.CookieOrigin;
import org.apache.http.cookie.CookieSpecFactory;
import org.apache.http.cookie.MalformedCookieException;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.impl.cookie.BrowserCompatSpec;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.parser.Parser;
import org.jsoup.select.Elements;

import com.google.appengine.labs.repackaged.org.json.JSONArray;
import com.google.appengine.labs.repackaged.org.json.JSONException;
import com.google.appengine.labs.repackaged.org.json.JSONObject;


@SuppressWarnings("serial")
public class Page extends HttpServlet {
	
	static final String LOGIN_URL = "https://www.shacknews.com/account/signin";
	static final String PAGE_URL = "http://www.shacknews.com/chatty";
	static final String USER_AGENT = "shackbrowseAPI/1.0";
	
	class Thread
	{
		String body;
		String category;
		String postId;
		String author;
		String date;
		int reply_count = 1;
		boolean replied = false;
	}
	
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		
		resp.setContentType("application/json; charset=UTF-8");
		
		String user = req.getParameter("user");
		String page = req.getParameter("page");
		
		if (page == null)
			page = "1";
		if (user == null)
			user = "912830jlkjdsljannc";		
		

        Document doc = Jsoup.parse(LoginDownload.get(PAGE_URL + "?page=" + page));
		
		Elements threads = doc.select("div.threads > div.root");
		
		JSONArray comments = new JSONArray();
		for (Element thisEl : threads)
		{
			Thread res = new Thread();
			Element fullPost = thisEl.getElementsByClass("fullpost").get(0);
			Set<String> names = fullPost.classNames();
			for (String name : names)
			{
				if (name.contains("fpmod_"))
					res.category = name.substring(6);
			}
			Elements userels = fullPost.getElementsByClass("user");
			if (userels.size() > 0)
			{
				Element child = userels.get(0);
				if (child.children().size() > 0)
					res.author = fullPost.getElementsByClass("user").get(0).child(0).ownText();
				else
					res.author = "Appspot_API_Err";
			}
			res.postId = thisEl.id().substring(5);
			res.date = fullPost.getElementsByClass("postdate").get(0).ownText();
			res.body = fullPost.getElementsByClass("postbody").get(0).html();
			
			try {
				Elements replycapcont = thisEl.getElementsByClass("capcontainer");
				if (replycapcont != null && replycapcont.size() > 0)
				{
	    			Element replycont = replycapcont.get(0).getElementsByTag("ul").get(0);
	    			// plus 1 to count root
	    			res.reply_count = 1 + replycont.getElementsByAttributeValueStarting("id", "item_").size();
	    			
	    			Pattern p = Pattern.compile("^" + user + "$", Pattern.CASE_INSENSITIVE);
	    			Elements containingUser = replycont.getElementsMatchingText(p);
	    			if (containingUser != null)
	    				res.replied = (containingUser.size() > 0);
				}
			}
			catch (Exception h) { resp.getWriter().println("ERROR CHECKING REPLIES" + res.postId); }
			
			
			
			JSONObject result = new JSONObject();
			
			try {
				result.put("id", res.postId);
				result.put("author", res.author);
				result.put("date", res.date);
				result.put("body", res.body);
				result.put("category", res.category);
				result.put("reply_count", res.reply_count);
				result.put("replied", res.replied);
			} catch (JSONException f) {
				// TODO Auto-generated catch block
				f.printStackTrace();
			}
			
			comments.put(result);
		}
		JSONObject container = new JSONObject();
		try {
			container.put("comments", comments);
		} catch (JSONException g) {
			// TODO Auto-generated catch block
			g.printStackTrace();
		}
		resp.getWriter().print(container.toString());
        
	}
}
